<template>
  <div  class="address-input">
    <Select :style="innerStyle" v-model="basicValue" :filterable="filterable" @on-change="selectChange" @on-query-change="queryChange" :disabled="disabled" :placeholder="placeholder" :placement="placement">
      <Option v-for="item in basicData" :value="item.id" :key="item.id">{{ item.name }}</Option>
    </Select>
  </div>
</template>

<script>
  import Ajax from '../../js/Ajax/index.js'

  Ajax.init({
    baseUrl: '',          // 是否设置 http(s)://***.com/, 即 http_origin，默认为空
    apiList: {}    // http请求地址的字典型
        // checkToken: false     // 是否在每个请求的头部设置token，默认为true
  })

  var getData = Ajax.methods

  var  PROVINCES_URL

  if (window.F2ESDK_CONFIG && window.F2ESDK_CONFIG.apiServer && window.F2ESDK_CONFIG.apiServer.PROVINCES_URL){
      PROVINCES_URL = window.F2ESDK_CONFIG.apiServer.PROVINCES_URL
  }

  const API_LIST =  PROVINCES_URL ||  'http://192.168.10.202:7801/pubdata'    //provinces ///cities  http://192.168.10.202:7801/pubdata


  export default {
    props: {
      // 用户自定义URL
      basicUrl: {
        type: String
      },
      // 选择框类型 省|province  市|city   区/district
      type: {
        type: String,
        default: 'province',
        validator: function (value) {
          if (value) {
            value = value.toLowerCase()
            return value === 'province' || value === 'city' || value === 'district'
          }
          return false
        }
      },
      // 创建时的默认值
      defaultValue: {
        type: String
      },
      // 市区用来加载列表时的父id
      parentId: {
        type: String
      },
      // 是否禁用
      disabled: {
        type: Boolean,
        default: false
      },
      // 未输入时显示的提示
      placeholder: {
        default: '请选择'
      },
      // 下拉框展开方向
      placement: {
        type: String,
        default: 'bottom'
      },
      // 是否支持搜索
      filterable: {
        type: Boolean,
        default: false
      },
      // style
      innerStyle: {
        type: Object,
        default () {
          return {
            width: '200px'
          }
        }
      }
    },
    data: function () {
      return {
        basicData: [],
        // Select 组件 v-model的值
        basicValue: ''
      }
    },
    methods: {
      getSelect () {
        var data = this.basicData
        var row
        for (let i = 0; i < data.length; i++) {
          if (data[i].id === this.basicValue) {
              row = data[i]
              break
          }
        }
        return row
      },
      // 选中框事件
      selectChange: function (val) {
        this.$emit('on-input', val, this.getSelect())
        this.$emit('select-change', val, this.getSelect())
      },
      // 搜索行变化事件
      queryChange: function (query) {
        // 传递事件
        this.$emit('query-change', query)
      },
      // 加载成功回调函数
      onloadSuccess: function (data) {
        this.$emit('onload-success', data)
      },
      // 加载失败，返回错误信息
      onError: function (error) {
        this.$emit('on-error', error)
      },
      // 加载前回调函数
      beforeLoad: function () {
        this.$emit('before-load')
      },
      // 获取数据
      getData: function () {
        var that = this
        var url
        var filedId
        var filedName
        var filedCode
        // 根据type 和 basicUrl 定义URL
        if (!that.basicUrl) { // 没有自定义url
            switch (that.type) {
                case 'province':
                    url = API_LIST + '/provinces'
                    filedId = 'provinceId'
                    filedName = 'provinceName'
                    filedCode = 'provinceCode'
                    break
                case 'city':
                    url = API_LIST + '/provinces' + '/' + that.parentId + '/cities'
                    filedId = 'cityId'
                    filedName = 'cityName'
                    filedCode = 'cityCode'
                    break
                case 'district':
                    url = API_LIST + '/cities' + '/' + that.parentId + '/districts'
                    filedId = 'districtId'
                    filedName = 'districtName'
                    filedCode = 'districtCode'
                    break
                default:
                    console.log('^^^^^^^*********^^^^^^^')
            }
        } else {
          // 自定义url
          url = that.basicUrl
        }
        getData.getUrl(url).then(function (res) {
          if (res.data.resultCode === 0) {
            that.basicData = []
            for (var i = 0; i < res.data.data.length; i++) {
              that.basicData.push({
                id: res.data.data[i][filedId],
                name: res.data.data[i][filedName],
                code: res.data.data[i][filedCode]
              })
            }
            that.realData = res.data.data
            that.onloadSuccess(res.data.data)
          } else {
            that.onError(res.data.resultMsg)
          }
        })
      }
    },

    mounted: function () {
      this.beforeLoad()
      this.basicValue = this.defaultValue
      // 如果是省选择框 直接查询 如果是市区则需要上级ID存在后再查询
      if (this.type === 'province' || ((this.type === 'city' || this.type === 'district') && this.parentId)) {
        this.getData()
      }
    },
    watch: {
      // 如果上级ID发生了变化重新加载数据
      parentId (newValue, oldValue) {
        this.basicData = []
        if (newValue && this.type && (this.type === 'city' || this.type === 'district')) {
          this.parentId = newValue
          this.getData()
        }
      },
      defaultValue (newValue, oldValue) {
        this.basicValue = newValue
      }
    }

  }
</script>

<style scoped lang="scss">
  .address-input {
    display: inline-block;
  }
</style>

